package com.api.common.alert.notififer;

import com.api.common.alert.model.AlertLevel;
import com.api.common.alert.model.AlertMessage;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.time.format.DateTimeFormatter;
import java.util.regex.Pattern;


/**
 * 邮件通知器
 */
@Component
@Slf4j
@ConditionalOnProperty(prefix = "alert.email",name = "enabled",havingValue = "true")
public class EmailNotifier implements Notifier{

    @Resource
    private  JavaMailSender mailSender;

    @Value("${alert.email.enabled:false}")
    private boolean enabled;

    @Value("${alert.email.from}")
    private String from;

    @Value("${alert.email.to}")
    private String to;

    @Value("${alert.email.subject-prefix:【API系统回复告警】}")
    private String subjectPrefix;
    private static final String EMAIL_REGEX =
            "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$";
    private static final Pattern EMAIL_PATTERN=Pattern.compile(EMAIL_REGEX);


    public void setTo(String to) {
        if(StringUtils.isBlank(to)||EMAIL_PATTERN.matcher(to).matches())
            throw new RuntimeException("邮件格式错误");
        this.to = to;
    }

    @Override
    public String getChannel() {
        return "email";
    }

    @Override
    public boolean isEnabled() {
        return enabled;
    }

    @Override
    public void send(AlertMessage event) {
        if (!enabled) {
            log.debug("邮件通知未启用");
            return;
        }

        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");

            helper.setFrom(from);
            helper.setTo(to.split(","));
            helper.setSubject(subjectPrefix + " " + event.getLevel().getName() + " - " + event.getAlertType());

            String htmlContent = buildHtmlContent(event);
            helper.setText(htmlContent, true);

            mailSender.send(message);

            log.info("邮件告警发送成功 | 类型={}, 收件人={}", event.getAlertType(), to);

        } catch (Exception e) {
            log.error("邮件告警发送失败 | 类型={}, 原因={}", event.getAlertType(), e.getMessage(), e);
        }
    }

    /**
     * 构建HTML邮件内容
     */
    private String buildHtmlContent(AlertMessage event) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        StringBuilder html = new StringBuilder();
        html.append("<!DOCTYPE html>");
        html.append("<html>");
        html.append("<head><meta charset='UTF-8'></head>");
        html.append("<body style='font-family: Arial, sans-serif; padding: 20px;'>");

        // 标题
        String levelColor = getLevelColor(event.getLevel());
        html.append("<div style='background-color: ").append(levelColor)
                .append("; color: white; padding: 15px; border-radius: 5px;'>");
        html.append("<h2 style='margin: 0;'>").append(event.getLevel().getIcon())
                .append(" ").append(event.getLevel().getName()).append("告警</h2>");
        html.append("</div>");

        // 内容
        html.append("<div style='margin-top: 20px; padding: 15px; background-color: #f5f5f5; border-left: 4px solid ")
                .append(levelColor).append(";'>");

        html.append("<p><strong>告警类型：</strong>").append(event.getAlertType()).append("</p>");
        html.append("<p><strong>告警源：</strong>").append(event.getSource()).append("</p>");
        html.append("<p><strong>告警时间：</strong>").append(event.getTimestamp().format(formatter)).append("</p>");

        if (event.getTraceId() != null) {
            html.append("<p><strong>追踪ID：</strong>").append(event.getTraceId()).append("</p>");
        }

        html.append("<p><strong>详细信息：</strong></p>");
        html.append("<div style='background-color: white; padding: 10px; border-radius: 3px;'>");
        html.append(event.getMessage().replace("\n", "<br>"));
        html.append("</div>");

        // 上下文数据
        if (event.getContext() != null && !event.getContext().isEmpty()) {
            html.append("<p><strong>附加信息：</strong></p>");
            html.append("<ul>");
            event.getContext().forEach((key, value) -> {
                html.append("<li><strong>").append(key).append("：</strong>").append(value).append("</li>");
            });
            html.append("</ul>");
        }

        html.append("</div>");

        // 页脚
        html.append("<div style='margin-top: 20px; padding: 10px; color: #666; font-size: 12px; border-top: 1px solid #ddd;'>");
        html.append("<p>此邮件由 AI 自动回复系统自动发送，请勿直接回复。</p>");
        html.append("</div>");

        html.append("</body>");
        html.append("</html>");

        return html.toString();
    }

    private String getLevelColor(AlertLevel level) {
        switch (level) {
            case CRITICAL:
                return "#d9534f";  // 红色
            case HIGH:
                return "#f0ad4e";  // 橙色
            case MEDIUM:
                return "#5bc0de";  // 蓝色
            case INFO:
                return "#5cb85c";  // 绿色
            default:
                return "#777";
        }
    }
}
